package pro.uccs.util;

import org.springframework.util.StringUtils;
import pro.uccs.constant.OCConstant;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/1/15.
 */
public class EncryptUtil {
    /**
     *
     * @param params 参数列表
     * @param secret 应用secret
     * @param signMethod 加密方式 使用MD5/HMAC加密
     * @return
     * @throws IOException
     */
    public static String paramSign(Map<String, String> params, String secret,
        String signMethod) throws IOException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        if (OCConstant.SIGN_METHOD_MD5.equals(signMethod)) {
            query.append(secret);
        }
        for (String key : keys) {
            String value = params.get(key);
            System.err.println("key:" + key + ",value:" + value);
            if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(value)) {
                query.append(key).append(value);
            }
        }

        // 第三步：使用MD5/HMAC加密
        byte[] bytes;
        if (OCConstant.SIGN_METHOD_HMAC.equals(signMethod)) {
            bytes = encryptHMAC(query.toString(), secret);
        } else {
            query.append(secret);
            bytes = encryptMD5(query.toString());
        }
        // 第四步：把二进制转化为小写的十六进制
        return MD5Coder.encryptMD516(query.toString());
    }

    public static byte[] encryptHMAC(String data, String secret)
        throws IOException {
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(
                secret.getBytes(OCConstant.CHARSET_UTF8), "HmacMD5");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(data.getBytes(OCConstant.CHARSET_UTF8));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse.toString());
        }
        return bytes;
    }

    public static byte[] encryptMD5(String data) throws IOException {
        return data.getBytes(OCConstant.CHARSET_UTF8);
    }

    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }

    public static String paramObjSign(Map<String, Object> params, String secret,
                                      String signMethod) throws IOException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        if (OCConstant.SIGN_METHOD_MD5.equals(signMethod)) {
            query.append(secret);
        }
        for (String key : keys) {
            Object value = params.get(key);
            System.err.println("key:" + key + ",value:" + value);
            if (!StringUtils.isEmpty(key) && value!=null) {
                // if (ValidatorUtil.isUrl(value)) {
                // value = URLEncoder.encode(value, "UTF-8");
                // }
                query.append(key).append(value);
            }
        }


        // 第三步：使用MD5/HMAC加密
        byte[] bytes;
        if (OCConstant.SIGN_METHOD_HMAC.equals(signMethod)) {
            bytes = encryptHMAC(query.toString(), secret);
        } else {
            query.append(secret);
            bytes = encryptMD5(query.toString());
        }

        // 第四步：把二进制转化为大写的十六进制
        return MD5Coder.encryptMD516(query.toString());
    }

    public static void main(String[] args) throws IOException {
        Map<String, String> params =new HashMap<>();
        params.put("method","simba.enterprise.department.get.departmentIdList");
        params.put("client_id","3bf85bced3f717ee42053a81f31721ac");
        params.put("enterpriseId","3");
//        params.put("userNumber","17001");
//        params.put("groupNumber","222");
//        params.put("currentVersion","1");
//        params.put("pageSize","10");
        params.put("session","0");
        params.put("timestamp","1563940561986");
//        params.put("param_json","{\"userNumber\":70000005,\"friendNumber\":70000038,\"fgroupId\":0}");
        String secret ="ff4546c6cfdaab09af6227da8020a397";
        String SIGN_METHOD_MD5="md5";
        String signMethod = SIGN_METHOD_MD5;

        System.out.println(paramSign(params,secret,signMethod));
    }
}

